package com.jf.cloud.service.sysmanager.support.result;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.jf.cloud.service.sysmanager.common.util.Encoding;
import com.jf.cloud.service.sysmanager.common.util.JsonUtil;
import com.jf.cloud.service.sysmanager.common.util.StringUtil;

/**
 * HTTP接口返回结果处理器
 * 
 * @author 程伟平 创建时间：2013-05-10 10:21:52
 */
public class ResultHandler {

	/**
	 * 日志
	 */
	private static Log log = LogFactory.getLog(ResultHandler.class);

	/**
	 * 获取HTTP接口返回结果 data:结果数据
	 */
	public static String getResult(Object data) {
		return getResult(Encoding.UTF8, data);
	}

	/**
	 * 获取HTTP接口返回结果 data:结果数据 encoding:默认为UTF-8
	 */
	public static String getResult(String encoding, Object data) {
		String rs = "";
		try {
			if (!StringUtil.isNotEmpty(encoding)) {
				encoding = Encoding.UTF8;
			}
			rs = JsonUtil.toJSON(data);
			if (rs != null && encoding != null && !Encoding.UTF8.equals(encoding.toUpperCase())) {
				rs = new String(rs.getBytes("UTF-8"), encoding);
			}
		} catch (Exception e) {
			log.error("获取HTTP接口返回结果出错！", e);
		}
		return rs;
	}

	/**
	 * 获取HTTP接口错误结果 errorCode:错误代码 keyword:关键字
	 */
	public static String getErrorResult(String errorCode, String keyword) {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("opcode", errorCode);
		if (StringUtil.isNotEmpty(ResultCode.getErrorDesc(errorCode))) {
			result.put("reason", ResultCode.getErrorDesc(errorCode));
		} else {
			result.put("reason", ResultCode.getErrorDesc(errorCode) + (StringUtil.isEmpty(keyword) ? "" : "，参数名称：" + keyword));
		}
		return getResult(result);
	}

	/**
	 * 获取HTTP接口错误结果 errorCode:错误代码 keyword:关键字 message:错误消息
	 */
	public static String getErrorResult(String errorCode, String keyword, String message) {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("opcode", errorCode);
//		result.put("reason", ResultCode.getErrorDesc(errorCode) + (StringUtil.isEmpty(keyword) ? "" : "，参数名称：" + keyword) + "，" + message);
		if(StringUtil.isNotEmpty(message)){
			result.put("reason", message);
		}else{
			result.put("reason", ResultCode.getErrorDesc(errorCode) + (StringUtil.isEmpty(keyword) ? "" : "，参数名称：" + keyword) + "");
		}
		
		return getResult(result);
	}
	/**
	 * 获取HTTP接口错误结果 errorCode:错误代码
	 */
	public static String getErrorResult(String errorCode) {
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("opcode", errorCode);
		return ResultHandler.getResult(result);
	}
}
